<?php
namespace App\Api\Controllers;
use Common\ApiController;
use Common\Common;
use Common\Models\FUsersExtend;
use Common\Models\User;
use Library\ConstKey\RedisKey;
use Library\ConstKey\SystemKey;
use Library\Tools\CommonTools;
use Library\Tools\RedisTools;
use Library\Validators\INArray;
use Services\Api\TurnServices;
use ServicesApi\Response\ActivityTurnLinkResponse;
use ServicesApi\Response\GoodsTurnResponse;

class TurnController extends ApiController
{
    public function initialize()
    {
        parent::initialize();
    }


    /**
     * 商品转链接
     */
    public function goods_turnAction()
    {
        if (!INArray::platformSite($this->params['site'])) {
            $this->fail(-1, '站点错误');
        }
        if (!isset($this->params['goods_id']) || empty($this->params['goods_id'])) {
            $this->fail(-1, '商品id不能为空');
        }
        $redis_key = Common::redisKey($this->params);
        $res = (new RedisTools())->get($redis_key);
        if (!$res && !SystemKey::ISREDIS) {
            $TurnServices = new TurnServices();
            $res = $TurnServices->goods_turn($this->params['site'], $this->user_info, $this->params['goods_id'], $this->params['couponurl'], $this->params['source']);
            (new RedisTools())->set($redis_key,$res['data']);
            if(!$res['status']){
                $this->fail(-1,$res['msg']);
            }
            (new RedisTools())->set($redis_key,$res['data']);
        }
        $goodsTurnResponse = new GoodsTurnResponse($res['data']);
        $this->ok($goodsTurnResponse);
    }


    /**
     * 活动转链
     */
    public function activity_turnlinkAction(){
        if (!INArray::platformSite($this->params['site'])) {
            $this->fail(-1, '站点错误');
        }
        if (!isset($this->params['acSource']) || empty($this->params['acSource'])) {
            $this->fail(-1, '活动资源不为空');
        }
        $TurnServices = new TurnServices();
        $res = $TurnServices->activity_turnlink($this->params['site'], $this->user_info, $this->params['acSource'],$this->params['source']);
        if(!$res['status']){
            $this->fail(-1,$res['msg']);
        }
        $activityTurnLink = new ActivityTurnLinkResponse($res['data']);
        $this->ok($activityTurnLink);
    }


    /**
     * 拼多多备案
     */
    public function pdd_keep_on_recordAction()
    {
        $turnServices = new TurnServices();
        $responseReturn = $turnServices->pdd_keep_on_record($this->user_info);
        if($responseReturn['status']){
            $this->ok($responseReturn['data']);
        }
        $this->fail(-1,$responseReturn['msg']);
    }



    /**
     * 拼多多生成频道推广
     * 频道来源：4-限时秒杀,39997-充值中心, 39998-转链type，39999-电器城，39996-百亿补贴
     */
    public function site_turnAction()
    {
        $in     = ['pdd', 'taobao', 'jd', 'taobao'];
        $params = $this->params;
        if (!isset($params['site']) || empty($params['site'])) {
            $this->fail(-1, '站点不能为空');
        } else {
            if (!in_array($params['site'], $in)) {
                $this->fail(-1, '站点错误');
            } else {
                if ($params['site'] == 'pdd') {
                    if (empty($this->user_info['pdd_pid'])) {
                        $result = $this->created_pid($this->user_info);
                        if(!$result['code']){
                            $this->fail(-1,$result['msg']);
                        }
                    }
                    if(!isset($params['id']) || empty($params['id'])){
                        $this->fail(-1,'请输入频道来源');
                    }
                    $res = $this->pdd->site_turn($this->user_info['pdd_pid'],$params);
                    if(!$res['code']){
                        $this->fail(-1,$res['msg']);
                    }
                    $res['data']['app_url'] = str_replace("https://mobile.yangkeduo.com", "pinduoduo://com.xunmeng.pinduoduo", $res['data']['we_app_web_view_url']);
                    $data['url'] = $res['data'];
                    $this->ok($data);
                }
            }
        }
    }


    //拼多多生成 用于推广进宝官方主题，用户可以点击您的推广链接进入主题商品集合页进入购买下单
    public function site_generateAction(){
        $params = $this->params;
        $in     = ['pdd', 'taobao', 'jd', 'taobao'];
        if (!isset($params['site']) || empty($params['site'])) {
            $this->fail(-1, '站点不能为空');
        } else {
            if (!in_array($params['site'], $in)) {
                $this->fail(-1, '站点错误');
            } else {
                if ($params['site'] == 'pdd') {
                    if (empty($this->user_info['pdd_pid'])) {
                        $result = $this->created_pid($this->user_info);
                        if(!$result['code']){
                            $this->fail(-1,$result['msg']);
                        }
                    }
                    if(!isset($params['theme_ids']) || empty($params['theme_ids'])){
                        $this->fail(-1,'请输入主题ID列表');
                    }
                    $res = $this->pdd->site_generate($this->user_info['pdd_pid'],$params);
                    if(!$res['code']){
                        $this->fail(-1,$res['msg']);
                    }
                    //$res['data']['app_url'] = str_replace("https://mobile.yangkeduo.com", "pinduoduo://com.xunmeng.pinduoduo", $res['data']['we_app_web_view_url']);
                    //$data['url'] = $res['data'];
                    $this->ok($res);
                }
            }
        }
    }


    /**
     * 生成推广位
     */
    public function created_pid($user_info){
        $response_pdd = $this->pdd->Createppdid($user_info['phone']);
        $user         = new User();
        $user_arr     = $user->find_by_phone($user_info['phone']);
        if ($response_pdd['code']) {
            $user_arr['pdd_pid'] = $response_pdd['msg'];
            $result              = $user->save_user($user_arr);
            if ($result) {
                $cache = new BaseModel();
                $cache->del_cache("user_" . $user_info['id']);
            } else {
                return ['code'=>false,'msg'=>'获取拼多多授权失败'];
            }
        } else {
            $str_phone    = $user_info['phone'];
            $response_pdd = $this->pdd->Createppdid($str_phone . rand(1, 1000));
            if ($response_pdd['code']) {
                $user_arr['pdd_pid'] = $response_pdd['msg'];
                $result              = $user->save_user($user_arr);
                if ($result) {
                    $cache = new BaseModel();
                    $cache->del_cache("user_" . $user_info['id']);
                } else {
                    return ['code'=>false,'msg'=>'获取拼多多授权失败'];
                }
            }
        }
        return ['code'=>true,'msg'=>'创建成功'];
    }


    /**
     * 生成淘口令
     */
    public function taowordAction()
    {
        if (!isset($this->params['url']) || empty($this->params['url'])) {
            $this->fail(-1, '链接地址不能为空');
        }

        if (!isset($this->params['title']) || empty($this->params['title'])) {
            $this->fail(-1, '弹出内容不能为空，且需要大于5个字符');
        }

        if (!isset($this->params['image']) || empty($this->params['image'])) {
            $this->fail(-1, '请设置封面图片路径');
        }

        if (!isset($this->params['goods_id']) || empty($this->params['goods_id'])) {              //为了区分哪些商品转链了的
            $this->fail(-1, '商品id不能为空');
        }

        $redis_key = "taoword_{$this->params['user_id']}_{$this->params['goods_id']}";
        $res = (new RedisTools())->get($redis_key);
        if (!$res) {
            $res = $this->taobao->couponUrlToText($this->params);
            (new RedisTools())->set($redis_key,$res);
        }
        if ($res['code']) {
            //$result = "復製这条，({$res['data']})，进入【Tao宝】即可抢购";
            $result = "復制评论({$res['data']})\n去【tao寳】下单";
            $this->ok($result);
        } else {
            $this->fail(-1, $res['msg']);
        }

    }


    /**
     * 官方活动转链测试
     */
    public function activitylinkAction()
    {
        if (!isset($this->params['avid']) || empty($this->params['avid'])) {
            $this->fail(-1, '活动id不能为空');
        }
        $request = $this->taobao->activitylink($this->params['avid']);
        if ($request['code']) {
            echo $request['data'];
        }
    }


    /**
     * 活动转链
     */
    public function activity_turnAction()
    {
        if (!isset($this->params['avid']) || empty($this->params['avid'])) {
            $this->params['avid'] = '1571715733668';
        }
        $user      = new User();
        $user_info = $user->find_by_firstId($this->params['user_id']);
        if (empty($user_info['tb_rid'])) {
            $this->fail(-1, '用户没有淘宝授权');
        }
        $request = $this->taobao->activitylink($this->params['avid'], $user_info['tb_rid']);
        if ($request['code']) {
            $data['url']            = $request['data'];
            $return_params['url']   = $request['data'];
            $return_params['title'] = '欢迎进入活动会场';
            $return_params['image'] = 'http://jzcloud.jiruan.ltd/img/chanpin.jpg';
            $res                    = $this->taobao->couponUrlToText($return_params);
            if ($res['code']) {
                if ($this->params['avid'] = '1571715733668') {
                    $result = "饿了么无接触配送，安心吃，满35减5元大额红包天天享，復製这条，({$res['data']})，进入【Tao宝】即可抢购";
                } else {
                    $result = "復製这条，({$res['data']})，进入【Tao宝】即可抢购";
                }
            } else {
                $this->fail(-1, '淘口令转换失败');
            }
        } else {
            $this->fail(-1, '活动转链失败，该活动有可能已经下架');
        }
        $data_result["url"]     = $request['data'];
        $data_result["kouling"] = $result;
        $this->ok($data_result);
    }


}
